// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-15 17:07
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.DynamicPlan;

import org.junit.jupiter.api.Test;

@SuppressWarnings("ALL")
public class ReverseBits {
    /**
     * 翻转一位二进制位数使得连续一的长度最长
     */
    public int reverseBitsT(int num) {
        /*
            滑动窗口
         */
        int count = 0, c = 1, left = 0, right = 0, max = Integer.MIN_VALUE, tmp = 0;
        boolean flag = false;
        char[] chars = (Integer.toBinaryString(num)).toCharArray();
        if (chars.length == 1) {
            if (chars[0] == '0') {
                return 1;
            } else {
                return 2;
            }
        }
        while (right <= chars.length - 1) {
            while (chars[right] == '1' || c == 1) {
                if (right == chars.length - 1) {
                    break;
                }

                if (chars[right] == '0' && c == 1) {
                    flag = true;
                    c -= 1;
                    tmp = right++;
                } else {
                    ++right;
                }

            }
            count = right - left + 1;
            max = Math.max(max, count);
            if (right == chars.length - 1) {
                break;
            }
            left = tmp;
            c = 1;
        }
        return flag ? max : max + 1;
    }

    public int reverseBitsTT(int num) {
        // 动态规划
        int pre = 0, cur = 0, max = 1;
        for (int i = 0; i < 32; i++) {
            if (((num >> i) & 1) !=0) {
           // if ((num & (1 << i))!=0){
                cur++;
                pre++;
            } else {
                pre = cur + 1;
                cur = 0;
            }
            max = Math.max(max, pre);
        }

        return max;
    }

    public int reverseBits(int num) {
        int cur = 0;
        int insert = 0;
        int res = 1;
        for(int i = 0; i < 32; i++){
            if((num & (1 << i)) != 0){
                cur += 1;
                insert += 1;
            }else{
                insert = cur + 1;
                cur = 0;
            }
            res = Math.max(res , insert);
        }
        return res;
    }

    @Test
    public void shout() {
        System.out.println(Integer.toBinaryString(-1));
//        System.out.println(Integer.toBinaryString(2147483647).length());
//        System.out.println(reverseBits(2147483646));
//        System.out.println(reverseBits(2147483647));
//        System.out.println(reverseBits(255));
//        System.out.println(reverseBits(16));
        // System.out.println(0b1111);

        System.out.println(reverseBits(214766));
//        System.out.println(reverseBits(0));
    }

    @Test
    public void shout00() {
        System.out.println(Integer.toBinaryString(214766));
        for (int i = 0; i < 31; i++) {
            System.out.print(((214766 >> i) & 1) + "\t");
        }

    }
}
